<script setup lang="ts">
import { defineProps, ref, onMounted, onUnmounted, watchEffect} from 'vue';
import { useNotification} from "naive-ui";
import { Selector, Markdown, QrcodeImg} from '@/components/common'
import {PayCallParam} from "@/api/entity/RequestParam";
import { resultPayVo } from "@/api/entity/ResultParam"
import { requestCallPayment, verifyPaySuccessAPI } from "@/api";
import { copyEvent} from "@/utils/rest/browserVersion";
import { StripePay } from "@/views/dashboard/call/components";
import { PAY_METHOD, PAY_CLIENT, } from '@/api/api'
import {resultCustom} from "@/utils/rest/notifyHint";
import {constants} from "os";
import errno = module


const hint = useNotification()
const select_payment = ref('0')
const props = defineProps({
  apiKey: {
    type: String,
  }
})
const paymeent_channel = PAY_METHOD
const handlePaymentChannelChange = (newValue: number) => {
  select_payment.value = newValue
  RequestPay.value.data.channel = newValue
}
const select_client =  ref('not')
const handlePaymentClientChange = (newValue: string) => {
  select_client.value = newValue
  RequestPay.value.data.payPlatform = newValue
}
const payment_client_list = PAY_CLIENT


const resultPayDetail = ref()

const RequestPay = ref<PayCallParam>({
  apiKey: "",
  data: {
    orderNo: '',
    channel: 0,
    amount: '',
    webhook: '',
    payPlatform: '',
    describe: '',
    attach: '',
    openId: '',
    currency: ''
  }})
const testPaymentDetailResult = ref({
  text: "示例返回值, 此数据为假数据",
  code: 200,
  data:  {
    orderNo: "2024041900030617",
    paymentSignature: "https://qr.alipay.com/bax06349fjjd7qc7k6gl0029",
    paymentAmount: "12.00"
  },
  timestamp: 1713456187
})
watchEffect(() => {
  RequestPay.value.apiKey = props.apiKey
});

const paymentCallDetail = ref<resultPayVo | null>(null)

function requestPaymentBtn() {
  paymentCallDetail.value = null;

  requestCallPayment(RequestPay.value).then(res => {
    if (res.code === 200) {
      testPaymentDetailResult.value = res;
      paymentCallDetail.value = res.data;
      requestCount.value = 0;
      paymentSuccess.value = 0;
      startPolling(paymentCallDetail.value.orderNo)
    }
  })
}

// 计数器
const requestCount = ref<number>(0);
const paymentSuccess = ref(0)


// 创建一个轮询函数
const startPolling = (orderNo: string) => {
  const intervalId = setInterval(async () => {
    // 发送请求
    verifyPaySuccess(orderNo, 0)
    requestCount.value ++;
    // 检查是否达到轮询次数
    if (requestCount.value >= 30) {
      paymentSuccess.value = 2;
      // 清除定时器
      clearInterval(intervalId);
    }
  }, 1000); // 每秒发送一次请求

  // 在组件卸载时清除定时器
  onUnmounted(() => {
    clearInterval(intervalId);
  });
};


async function verifyPaySuccess(orderNo: string, type: number) {
  await verifyPaySuccessAPI({field: orderNo}).then(res => {
    const successDetail = res;
    if (successDetail.code == 200) {
      requestCount.value = 30
      paymentSuccess.value = 1
    }
    if (successDetail.code == 202) {
      requestCount.value = 30
      paymentSuccess.value = 2
    }
  }).catch(error =>{

  })
}



function copyOrderValue() {
    if (paymentCallDetail.value !== null ) {
      copyEvent(paymentCallDetail.value.orderNo, hint)
    }
}

</script>
<template>
  <div class="row w-100">
    <div class="col-lg-6">
      <div class="input-material-group mb-3 col-10 mx-auto d-flex">
        <div class="col-5 d-flex">
          <Selector class="w-100" :label="''" @change="handlePaymentChannelChange" :options="paymeent_channel" :value="select_payment" >
          </Selector>
        </div>
        <div class="ml-20 col-5 d-flex">
          <Selector class="w-100" @change="handlePaymentClientChange" :options="payment_client_list" :value="select_client">
          </Selector>
        </div>
      </div>


      <div class="input-material-group row  mb-3 col-10 mx-auto d-flex">
        <div class="col-lg-5 mb-3">
          <input
              v-model="RequestPay.data.amount"
              class="input-material"
              placeholder="价格"/>
        </div>
        <div class="col-lg-2 mb-3"></div>
        <div class="col-lg-5">
          <input
              v-model="RequestPay.data.webhook"
              class="input-material"
              placeholder="回调地址"/>
        </div>
      </div>

      <div class="input-material-group row col-10 mb-3  mx-auto d-flex">
        <div class="col-lg-5 mb-3">
          <input
              v-model="RequestPay.data.describe"
              class="input-material"
              placeholder="描述或标题"/>
        </div>
        <div class="col-lg-2 mb-3"></div>
        <div class="col-lg-5">
          <input
              v-model="RequestPay.data.orderNo"
              class="input-material"
              placeholder="订单号"/>
        </div>
      </div>


      <div class="input-material-group mb-3 col-10 mx-auto">
        <input
            v-model="RequestPay.data.attach"
            class="input-material"
            placeholder="附加数据"/>
      </div>

      <div class="input-material-group mb-3 col-10 mx-auto">
        <input
            v-model="RequestPay.data.openId"
            class="input-material"
            placeholder="openId 微信小程序必传"/>
      </div>
      <div class="col-10 mx-auto mb-10">
        <NButton class="w-100" type="info" @click="requestPaymentBtn">发送请求</NButton>
      </div>

      <div class="call-title w-40 mx-auto fs-5"> 请求Json数据</div>
      <div class="input-material-group mb-3 col-10 mx-auto">
        <Markdown :transform="RequestPay" language="json" ></Markdown>
      </div>
    </div>

    <div class="col-lg-6">
      <div class="call-title w-40 mx-auto fs-5"> 返回数据示例</div>

      <div class="input-material-group mb-3 col-10 mx-auto">
        <Markdown :transform="testPaymentDetailResult" language="json" ></Markdown>
      </div>

      <div class="call-title w-40 mx-auto fs-5">支付测试</div>
      <div class="input-material-group col-8 mx-auto ">

        <div v-if="paymentCallDetail" class="input-material-group">

            <div class="result-pay-order">订单号:
              <span class="ml-10">{{paymentCallDetail.orderNo}}</span>
              <span class="copy-text ml-4" @click="copyOrderValue">复制</span>
            </div>
            <div class="result-pay-amount">
              {{paymentCallDetail.paymentAmount}}
            </div>

        </div>


        <div v-if="paymentSuccess == 0 || paymentSuccess == 2">
          <div v-if="RequestPay.data.channel == 1 && paymentCallDetail" class="qr-code-container">
            <QrcodeImg :qrcode="paymentCallDetail.paymentSignature" width="250" color="#2F80ED" bgcolor="f1f1f1" />
            <div class="text-center text-primary">扫码测试下支付吧</div>
          </div>

          <div v-if="RequestPay.data.channel == 2 && paymentCallDetail">
            <StripePay :payDetail="paymentCallDetail"> </StripePay>
          </div>


          <NButton class="find-order" type="info" v-if="paymentSuccess == 2"
                   @click="verifyPaySuccess(paymentCallDetail.orderNo, 1)">
            查询是否支付成功
          </NButton>
        </div>

        <div v-if="paymentSuccess == 1">
          <div class="qr-code-container">
              <div class="pay-success">支付成功</div>
          </div>
        </div>

      </div>
    </div>
  </div>
</template>

<style scoped>
.call-title {
  color: #2F80ED;
}
.input-material-group {
  position: relative;
  padding-top: 0.85rem
}

.input-material-group .input-material {
  letter-spacing: 1px;
  border: none;
  outline: none;
  background: none;
  padding: .375rem 0;
  border-bottom: 1px solid #40444b;
  display: block;
  width: 100%;
}

.result-pay-amount{
  color: red;
  font-size: 28px;
  text-align: center;
}
.result-pay-order{
  color: #2F80ED;
  font-size: 20px;
  text-align: center;
}
.qr-code-container {
  width: 250px;
  margin: 0px auto;
  box-shadow: 0 0 1.5px #2F80ED;
}
.copy-text:hover {
  color: red;
  transform: scale(0.99);
}
.pay-success {
  text-align: center;
  line-height: 250px;
  font-size: 35px;
  color: #2F80ED;
  font-weight: bold;
}
.find-order{
  width: 100%;
  margin: 10px auto;
}

</style>
